<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkMessage\Service;

use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\WorkMessage\Contract\WorkMessageUserIdMappingContract;
use MoChat\App\WorkMessage\Model\WorkMessageUserIdMapping;
use MoChat\Framework\Service\AbstractService;
use Psr\SimpleCache\CacheInterface;

class WorkMessageUserIdMappingService extends AbstractService implements WorkMessageUserIdMappingContract
{
    /**
     * @var WorkMessageUserIdMapping
     */
    protected $model;

    /**
     * @var Builder
     */
    protected $query;

    /**
     * @Inject
     * @var CacheInterface
     */
    protected $cache;

    /**
     * {@inheritdoc}
     */
    public function __construct(int $corpId)
    {
        $this->model = make(WorkMessageUserIdMapping::class)->initTable($corpId);
        $this->query = Db::table($this->model->getTable());
    }

    /**
     * 查询单条 - 根据ID.
     * @param int $id ID
     * @param array|string[] $columns 查询字段
     * @return array 数组
     */
    public function getWorkMessageByCorpUserId(int $corp_id,string $user_id, array $columns = ['*']): array
    {
        $data = $this->newQuery()->where('corp_id', $corp_id)->where('user_id',$user_id)->first($columns);
        $data || $data = [];
        return (array) $data;
    }

    /**
     * 添加单条
     * @param array $data 添加的数据
     * @return int 自增ID
     */
    public function createWorkUserIdMappingMessage(array $data): int
    {
        $newData = $this->model->columnsFormat($data, true, true);
        return $this->newQuery()->insertOrIgnore($newData);
    }

    /**
     * 添加多条
     * @param array $data 添加的数据
     * @return bool 执行结果
     */
    public function createWorkUserIdMappingMessages(array $data): bool
    {
        $newData = array_map(function ($item) {
            return $this->model->columnsFormat($item, true, true);
        }, $data);
        return (bool) $this->newQuery()->insertOrIgnore($newData);
    }


    protected function newQuery()
    {
        return Db::table($this->model->getTable());
    }
}
